<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="100px"
  >
    <!-- 权限名称 -->
    <el-form-item label="权限名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入权限名称" clearable/>
    </el-form-item>

    <!-- 权限路径 -->
    <el-form-item label="权限路径" prop="purl">
      <el-input v-model="formData.purl" placeholder="请输入权限路径" clearable/>
    </el-form-item>

    <!-- 类型 -->
    <el-form-item label="类型" prop="type">
      <el-select v-model="formData.type" placeholder="请选择类型">
        <el-option label="组件" :value="1"/>
        <el-option label="方法" :value="2"/>
      </el-select>
    </el-form-item>

    <!-- 组件路径，仅在 type === 1（组件）时显示 -->
    <el-form-item v-if="formData.type === 1" label="组件路径" prop="component">
      <el-input v-model="formData.component" placeholder="请输入组件路径（如 views/Home.vue）" clearable/>
    </el-form-item>

    <!-- 父权限 -->
    <el-form-item label="父权限" prop="pid">
      <el-select v-model="formData.pid" placeholder="请选择父权限">
        <el-option label="无" :value="0"/>
        <el-option
          v-for="opt in permissionOptions"
          :key="opt.value"
          :label="opt.label"
          :value="opt.value"
        />
      </el-select>
    </el-form-item>

    <!-- 按钮区 -->
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { Permission, PermissionForm } from '@/types/rs/Permission'
import request from '@/util/request'
interface Props {
  permission?: Permission | null
}
const props = defineProps<Props>()
const emit = defineEmits(['submit-success', 'cancel'])

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

const formRef = ref<FormInstance>()
const formData = reactive<PermissionForm>({
  id: undefined,
  name: '',
  purl: '',
  type: undefined,
  component: '',
  pid: 0,
  createUser: user.user.name,
  updateUser: user.user.name,
})

const formRules = reactive<FormRules<PermissionForm>>({
  name: [{ required: true, message: '权限名称不能为空', trigger: ['blur','change'] }],
  purl: [{ required: true, message: '权限路径不能为空', trigger: ['blur','change'] }],
  type: [{ required: true, message: '类型不能为空', trigger: ['change'] }],
  component: [{
    required: () => formData.type === 1,
    message: '组件路径不能为空',
    trigger: ['blur','change']
  }],
  pid: [{ required: true, message: '父权限不能为空', trigger: ['change'] }]
})

const permissionOptions = ref<{ label: string; value: number }[]>([])

// 🚀 关键：watch 实现回显
watch(() => props.permission, (val) => {
  if (val) {
    formData.id = val.id
    formData.name = val.name
    formData.purl = val.purl
    // 后端 type 是字符串，转成 number
    formData.type = Number(val.type)
    // 如果 component 为 null/undefined，回显成空字符串
    formData.component = val.component ?? ''
    // pid 直接回写
    formData.pid = val.pid
  } else {
    formRef.value?.resetFields()
  }
}, { immediate: true })

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    const url = formData.id ? 'per/perm/update' : 'per/perm/add'
    const payload: any = {
      ...formData,
      is_delete: 0,
    }
    const res = await request.post(url, payload)
    if (res.data.code == '200' || res.data.code === 200) {
      ElMessage.success('操作成功')
      emit('submit-success')
    } else {
      throw new Error(res.data.msg || '操作失败')
    }
  } catch (err: any) {
    ElMessage.error(err.message || '提交失败，请检查数据')
  }
}

function handleReset() {
  formRef.value?.resetFields()
}

onMounted(async () => {
  try {
    const response = await request.get<{ code:string; msg:string|null; data: Permission[] }>('per/perm/getAll')
    if (response.data.code === '200' && Array.isArray(response.data.data)) {
      permissionOptions.value = response.data.data.map(p => ({
        label: p.name,
        value: p.id
      }))
    } else {
      throw new Error(response.data.msg || '加载数据失败')
    }
  } catch (err) {
    console.error(err)
    ElMessage.warning('加载父权限列表失败')
  }
})
</script>

<style scoped>
.el-form { padding: 20px; }
.el-form-item:last-child { text-align: right; margin-top: 20px; }
</style>
